package com.mallcloud.mall.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.mallcloud.mall.common.core.exception.FailException;
import com.mallcloud.mall.product.api.dto.AttrExtendDTO;
import com.mallcloud.mall.product.api.entity.SpuAttrValueModel;
import com.mallcloud.mall.product.api.entity.SpuSkuAttrValueModel;
import com.mallcloud.mall.product.api.vo.AttrExtendVO;
import com.mallcloud.mall.product.mapper.AttrMapper;
import com.mallcloud.mall.product.mapper.SpuAttrValueMapper;
import com.mallcloud.mall.product.service.SpuAttrValueService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品规格属性关联信息
 */
@Service
@AllArgsConstructor
public class SpuAttrValueServiceImpl extends ServiceImpl<SpuAttrValueMapper, SpuAttrValueModel> implements SpuAttrValueService {
    private final AttrMapper attrMapper;

    @Override
    public Boolean saveSpuAttrValue(SpuAttrValueModel dto) {
        if(this.count(Wrappers.<SpuAttrValueModel>lambdaQuery()
                .eq(SpuAttrValueModel::getSpuId, dto.getSpuId())
                .eq(SpuAttrValueModel::getAttrId, dto.getAttrId())
        ) > 0){
            throw new FailException("规格不能重复添加");
        }
        List<AttrExtendVO> attrExtends = attrMapper.extendAttr(Lists.newArrayList(new AttrExtendDTO(dto.getAttrId(), dto.getAttrValueId())));
        List<SpuAttrValueModel> collect = attrExtends.stream().map(x -> {
            SpuAttrValueModel m = BeanUtil.copyProperties(x, SpuAttrValueModel.class);
            m.setSpuId(dto.getSpuId());
            return m;
        }).collect(Collectors.toList());

        return this.save(collect.get(0));
    }
}
